package com.sylar.happyreader.tools;

import java.util.concurrent.Callable;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.sylar.happyreader.R;
import com.sylar.happyreader.listener.Callback;

public class TaskUtils {
	public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback) {
		TaskUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, false);
	}
	public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
		new AsyncTask<Void, Void, T>() {
			private ProgressDialog mPD;
			private Exception mException = null;
			
			public void onPreExecute() {
				try {
					this.mPD =  new ProgressDialog(pContext);
					this.mPD.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					this.mPD.setMessage(pMessage);
					this.mPD.show();
					if(pCancelable) {
						this.mPD.setOnCancelListener(new OnCancelListener() {
							
							public void onCancel(final DialogInterface pDialogInterface) {
								pExceptionCallback.onCallback(new CancelledException());
								pDialogInterface.dismiss();
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				super.onPreExecute();
			}
			
			public T doInBackground(final Void... params) {
				try {
					return pCallable.call();
				} catch (final Exception e) {
					this.mException = e;
				}
				return null;
			}
			
			public void onPostExecute(final T result) {
				try {
					this.mPD.dismiss();
				} catch (final Exception e) {
					Log.e("Error", e.toString());
				}
				if(this.isCancelled()) {
					this.mException = new CancelledException();
				}
				if(this.mException == null) {
					pCallback.onCallback(result);
				} else {
					if(pExceptionCallback == null) {
						if (this.mException != null){
							Log.e("Error", this.mException.toString());
							Toast.makeText(pContext, "加载失败啦", 1).show();
						}
						
					} else {
						pExceptionCallback.onCallback(this.mException);
					}
				}
				super.onPostExecute(result);
			}
		}.execute((Void[]) null);
	}
	
	public static class CancelledException extends Exception {
		private static final long serialVersionUID = -78123211381435595L;
	}
}
